const loginBtn = document.getElementById('loginBtn');
const registerBtn = document.getElementById('registerBtn');
const contentGenBtn = document.getElementById('contentGen');
const explainQuestionBtn = document.getElementById('explainQuestionBtn');


document.addEventListener('DOMContentLoaded', () => {
    loginBtn.addEventListener('click', showLoginModal);
    registerBtn.addEventListener('click', showRegisterModal);
    contentGenBtn.addEventListener('click', function() {
        window.location.href = "/ai4stu"; // 替换成你要跳转的地址
    })
    
    // 题目讲解按钮点击事件
    if (explainQuestionBtn) {
        explainQuestionBtn.addEventListener('click', function() {
            // 实现题目讲解功能
            showPostModal();
        });
    }
    
    // logout();
    updateAuthState();
});

function showLoginModal() {
    modalBody.innerHTML = `
        <h2>登录</h2>
        <div class="form-group">
            <label for="loginUsername">用户名</label>
            <input type="text" id="loginUsername" placeholder="输入用户名">
        </div>
        <div class="form-group">
            <label for="loginPassword">密码</label>
            <input type="password" id="loginPassword" placeholder="输入密码">
        </div>
        <button id="loginConfirm">登录</button>
    `;

    modal.style.display = 'block';

    document.getElementById('loginConfirm').addEventListener('click', login);
}

function showRegisterModal() {
    modalBody.innerHTML = `
        <h2>注册</h2>
        <div class="form-group">
            <label for="registerName">用户名</label>
            <input type="text" id="registerName" placeholder="输入用户名">
        </div>
        <div class="form-group">
            <label for="registerPassword">密码</label>
            <input type="password" id="registerPassword" placeholder="输入密码">
        </div>
        <button id="registerConfirm">注册</button>
    `;

    modal.style.display = 'block';

    document.getElementById('registerConfirm').addEventListener('click', register);
}

function login() {
    const loginUsername = document.getElementById('loginUsername').value;
    const loginPassword = document.getElementById('loginPassword').value;

    // 显示加载动画
    modal.style.display = 'none';
    document.getElementById('upload-loading').style.display = 'block';
    
    fetch('/api/login', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({ loginUsername, loginPassword })
    })
    .then(response => {
            if (response.status === 200 || response.status === 201) {
                // 保存用户名到localStorage
                localStorage.setItem('username', loginUsername);
                updateAuthState();
                location.reload();
            } else {
                alert('登录失败: ' + response.statusText);
            }
        })
    .catch(error => console.error('登录错误:', error))
    .finally(() => {
        document.getElementById('upload-loading').style.display = 'none';
    });

}

function register() {
    const registerName = document.getElementById('registerName').value;
    const registerPassword = document.getElementById('registerPassword').value;

    // 显示加载动画
    modal.style.display = 'none';
    document.getElementById('upload-loading').style.display = 'block';

    fetch('/api/register', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({ registerName, registerPassword })
    })
    .then(response => response.json())
    .then(data => {
        if (data.message) {
            document.getElementById('upload-loading').style.display = 'none';
            alert('注册成功，请登录');
            showLoginModal();
        } else {
            alert('注册失败: ' + (data.error || '未知错误'));
        }
    })
    .catch(error => console.error('注册错误:', error))
    .finally(() => {
        // 隐藏加载动画
        document.getElementById('upload-loading').style.display = 'none';
    });
}

function getCookie(name) {
    const cookies = document.cookie.split('; ');
    for (let cookie of cookies) {
        const [key, value] = cookie.split('=');
        if (key === name) return value;
    }
    return null;
}

function updateAuthState() {
    const token = getCookie('token'); // 获取 cookie 中的 token
    const loginBtn = document.getElementById('loginBtn');  // 确保 loginBtn 被正确获取
    const registerBtn = document.getElementById('registerBtn'); // 获取注册按钮
    const pathElement = document.querySelector('.path'); // 获取路径显示元素
    
    if (!loginBtn) {
        console.error("登录按钮未找到！");
        return;
    }
    
    // 更新路径显示
    if (pathElement) {
        if (token) {
            const username = localStorage.getItem('username') || '用户';
            pathElement.textContent = username;
        } else {
            pathElement.textContent = '未登录';
        }
    }
    
    // 清除旧的监听器，避免重复绑定
    loginBtn.replaceWith(loginBtn.cloneNode(true));
    const newLoginBtn = document.getElementById('loginBtn'); // 重新获取新的按钮节点
    if (token) {
        newLoginBtn.textContent = '退出登录';
        newLoginBtn.addEventListener('click', logout);
        // 隐藏注册按钮
        if (registerBtn) {
            registerBtn.style.display = 'none';
        }
        loadFileList?.();  // 可选链调用，防止 loadFileList 未定义时报错
    } else {
        newLoginBtn.textContent = '登录';
        newLoginBtn.addEventListener('click', showLoginModal);
        // 显示注册按钮
        if (registerBtn) {
            registerBtn.style.display = 'inline-block';
        }
    }
}

function logout() {
    // 删除 cookie（设置过期时间）
    document.cookie = "token=; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT";
    // 删除localStorage中的用户名
    localStorage.removeItem('username');
    // 更新 UI 状态
    updateAuthState();
    // 可选：跳转到登录页或刷新页面
    location.reload();
    alert('已退出登录');
}
